import {WeaDialog, WeaTableEdit} from 'ecCom';
import {Button, DatePicker, TimePicker, Form, Modal, message} from 'antd';
import moment from 'moment';
import {toJS} from 'mobx'
import * as Apis from '../../../../apis/dialog';
import mapKeys from 'lodash/mapKeys';
import mapValues from 'lodash/mapValues';
const FormItem = Form.Item;
import {inject, observer} from 'mobx-react';
import {WeaLocaleProvider, WeaRangePicker, WeaUpload} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

@inject('meetingDialog')
@observer
class MeetTopicTidyDialog extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      datas:[],
      columns:[],
      rowIndex:1,
    };
    this.arrangeRef = React.createRef();
  }

  render() {
    let {visible,datas,columns} = this.state;
    let {titleKey} = this.props;
    const {setEditTableCloumnCount, topicTidyDialogHeight, setState} = this.props.meetingDialog;

    const scrollParams = (cloumn, height) => {
      return {
        x: cloumn.length > setEditTableCloumnCount ? 100*cloumn.length : '', 
        y: height-45-40
      };
    };
    const dialogHeight = 400;
    let noScale = `scalable no-scalable-${columns.length}`;
    if(columns.length >= 8) {
      noScale = 'scalable no-scalable';
    }
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@q5b6tp`} visible={visible}
        ref={this.arrangeRef}
        title={`${getLabel(519704, "整理议程")}`}
        className='wea-meeting-arrange'
        style={{width: 790, height: dialogHeight}}
        icon="icon-coms-meeting"
        iconBgcolor="#f14a2d"
        hasScroll = 'true'
        onCancel={this.back}
        scalable={true}
        onScale={() => {
          setTimeout(() => {
            if(this.arrangeRef.current) {
              setState({ topicTidyDialogHeight: this.arrangeRef.current.state.height });
            }
          }, 0);
        }}
        buttons={[
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zwnhhu@doSubmit`} type="primary" onClick={this.submit}>{getLabel(383336, "提交")}</Button>,
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bsk0lo@doBack`} onClick={this.back}>{getLabel(83823, "返回")}</Button>
        ]}>
        <div className="wea-meeting-topic-time" params={topicTidyDialogHeight}>
          
          {columns.length>0&&<WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@qpifol`}
            className={topicTidyDialogHeight == dialogHeight ? `meeting-tidy-edittable ${noScale}` : 'meeting-tidy-edittable'}
            ref='topicEdit'
            title={getLabel(383558,"议程列表")}
            datas={datas}
            columns={columns}
            onChange={datas => { this.tableEditChange(datas); }}
            viewAttr={2}
            tableProps={{scroll: scrollParams(columns, topicTidyDialogHeight)}}
            onCopy={(keys,datas)=>{this.setCopyIndex(keys)}}
            draggable={true}
          />}
        </div>
      </WeaDialog>
    );
  }

  open = () => {
    let {setTopicTidyResultDatas,setTopicTidyDatas} = this.props.meetingDialog;
    setTopicTidyResultDatas({})
    setTopicTidyDatas({})
    this.setState({
      visible: true,
      datas: []
    }, () => {
      let {meetingId} = this.props;
      let {oldSecretLevel, accessoryBaseInfo, arrangeTopicParams} = this.props.meetingDialog;
      const params = {
        meetingid: meetingId,
        ...arrangeTopicParams
      };
      Apis.getMeetingTopicField(params).then((result) => {
        let newTop = result.columns;
        let columns_topicField = '';
        if(newTop){
          let countTop = 100 / newTop.length;
          columns_topicField = newTop.map((x) => {
            let viewattr = x.com && x.com[0] && x.com[0].viewAttr;
            if(x.width === undefined) {
              x['width'] = `${countTop}%`;
            }
            x['className'] = x.dataIndex;
            if (x.com&&x.com[0].type == 'BROWSER') {
              x.com[0].browserConditionParam.layout = document.body
              x.com[0].browserConditionParam.dataParams = {...x.com[0].browserConditionParam.dataParams,secretLevel: oldSecretLevel}
              x.com[0].browserConditionParam.completeParams = {...x.com[0].browserConditionParam.completeParams,secretLevel: oldSecretLevel}
            }
            if (x.com&&x.com[0].type == 'FILEDUPLOAD') {
              let otherParams = x.com[0].otherParams&&x.com[0].otherParams || {}
              let listType = otherParams&&otherParams.listType || ''
              let uploadUrl = accessoryBaseInfo.uploadUrl
              if(listType == 'img' && uploadUrl.indexOf('listType=img') < 0){
                uploadUrl = uploadUrl+"&listType=img"
              }
              return {
                title:x.title,
                key:x.key,
                dataIndex:x.dataIndex,
                width: x.width ? x.width : `${countTop}%`,
                com:[{
                  type: 'custom',
                  key: x.key,
                  viewAttr: viewattr,
                  render: (text, record, index, onEdit) => {
                    return <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@1qz4mo@${x.key}_${index}`}
                      btnSize='small'
                      {...accessoryBaseInfo}
                      {...otherParams}
                      uploadUrl = {uploadUrl}
                      viewAttr={viewattr}
                      autoUpload={true}//自动上传
                      isDetail={true}
                      showClearAll={false}
                      datas={record[x.dataIndex].datas}
                      onChange={(ids, list) => {
                        onEdit({
                          record: {
                            ...record,
                            [x.key]: {
                              datas: list
                            },
                          }, 
                          index, 
                        })
                      }}
                    >
                    </WeaUpload>
                  }
                }
                ]
              }
            }
            return x
          })
        }
        this.setState({datas:result.datas,columns:columns_topicField,rowIndex:result.rowIndex})
        this.tableEditChange(result.datas)
      });
    });
  }

  back = () => {
    this.setState({
      visible: false,
      record: {},
      datas:[]
    });
  }

  setCopyIndex = (value)=>{
    let {setCopyIndex} = this.props.meetingDialog;
    setCopyIndex(value)
  }

  tableEditChange=(datas)=>{
    let {setTopicTidyResultDatas,setTopicTidyDatas,setCopyIndex,copyIndex} = this.props.meetingDialog;
    if(copyIndex.length>0 && copyIndex[0] != 0){
      copyIndex.forEach((v,idx)=>{
        datas[v].topic_data = '';
      })
      setCopyIndex([0]);
    }
    setTopicTidyDatas(datas)
    this.setState({datas:datas})
    let alldatas = {};
    let each = {};
    datas.forEach((element, index) => {
      each = mapKeys(element, (value, key) => {
        return key + '_' + (index+1)
      })
      alldatas = {...alldatas, ...each}
    })
    alldatas = mapValues(alldatas, (value, key) => {
      let t_value = value;
      if (value && value.datas) { // 附件特殊处理 附件保存附件id
        if(value.datas instanceof Array) {
          let arr = [];
          value.datas.map(res => {
            arr.push(res.fileid);
          })
          t_value = arr.join(',');
        }
      }
      return t_value;
    })
    let topicrows = datas.length;
    alldatas = {
      ...alldatas,
      topicrows: topicrows || 0,
    }
    setTopicTidyResultDatas(alldatas)
  }

  submit = () => {
    let {meetingId} = this.props;
    let {saveTopicTidyDatas} = this.props.meetingDialog;
    if(this.refs.topicEdit.refs.edit.doRequiredCheck().pass){
      saveTopicTidyDatas({meetingid:meetingId},this.back)
    }else{
      message.error(`${getLabel(384010, '存在必填项未填写')}`);
    }
    
  }

}

export default MeetTopicTidyDialog;